import React, { Profiler, useState, useRef } from "react";
import { useEffect } from "react";
import create from "zustand";
import product from "immer";

const useCountStore = create((set, get) => ({
  a: { b: 1, b2: 1 },
  add: () => set((store) => ({ a: { ...store.a, b: store.a.b + 1 } })),
  add2: () => set((store) => ({ a: { b: store.a.b + 1 } })),
  add3: () =>
    set((store) =>
      product(store, (newStore) => {
        newStore.a.b++;
      })
    ),
}));
let rerenderCount = 0;
function Component1() {
  const { b, b2, add, add2, add3 } = useCountStore((store) => ({
    b: store.a.b,
    b2: store.a.b2,
    add: store.add,
    add2: store.add2,
    add3: store.add3,
  }));

  return (
    <>
      <ul>
        <li>rerenderCount: {++rerenderCount}</li>
        <li>
          store.a.b: {b} <br />
          store.a.b2: {b2}
        </li>
        <li>
          <button onClick={add}>add1</button>
          <button onClick={add2}>add2</button>
          <button onClick={add3}>add3</button>
        </li>
      </ul>
    </>
  );
}
let rerenderCount2 = 0;
function Component2() {
  const { b } = useCountStore((store) => ({
    b: store.a.b,
  }));
  return (
    <>
      <ul>
        <li>rerenderCount: {++rerenderCount2}</li>
        <li>
          store.a.b: {b} <br />
        </li>
      </ul>
    </>
  );
}

function App() {
  const onRender = (...props) => {
    console.log("onRender", props);
  };
  return (
    <Profiler id="App" onRender={onRender}>
      <div>
        <h1>Component1</h1>
        <Component1 />

        <h1>Component2</h1>
        <Component2 />
      </div>
    </Profiler>
  );
}

export default App;
